﻿using System;
using System.Collections.Generic;
using System.Data;

namespace DBMock
{
    /// <summary>
    /// 行builder
    /// </summary>
    public class RowBuilder
    {
        //随机数生成器
        private Random random;

        /// <summary>
        /// 策略集合
        /// </summary>
        public List<Strategy> Strategies { get; private set; }

        /// <summary>
        /// 单元格builder组集合
        /// </summary>
        public List<Builder[]> BuilderGroups { get; private set; }

        /// <summary>
        /// 验证器集合
        /// </summary>
        public List<Validator[]> ValidatorGroups { get; private set; }

        /// <summary>
        /// 初始化行builder
        /// </summary>
        /// <param name="builderGroups"></param>
        public RowBuilder(List<Strategy> strategies, List<Builder[]> builderGroups, List<Validator[]> validatorGroups)
        {
            random = new Random();

            Strategies = strategies;
            BuilderGroups = builderGroups;
            ValidatorGroups = validatorGroups;
        }

        /// <summary>
        /// Build行
        /// </summary>
        /// <param name="row">行</param>
        public void Build(DataRow row)
        {
            int colCount = row.ItemArray.Length;
            CacheHelper.Clear(CacheType.STRATEGY_ID);

            if (Strategies == null || Strategies.Count != colCount ||
                BuilderGroups == null || BuilderGroups.Count != colCount)
            {
                return;
            }

            for (int i = 0; i < colCount; i++)
            {
                var group = BuilderGroups[i];

                var strategy = Strategies[i];
                int strategyID = random.Next(group.Length);

                if (strategy != null)
                { strategyID = CacheHelper.Get(strategy.Name, CacheType.STRATEGY_ID, n => strategyID); }

                var builder = group == null || group.Length == 0 || strategyID >= group.Length ?
                    null : group[strategyID];

                if (builder == null || (random.Next(1, 101) <= builder.NullPercent))
                {
                    row[i] = DBNull.Value;
                    continue;
                }

                row[i] = builder.Build();
            }

            if (ValidatorGroups == null || ValidatorGroups.Count != colCount)
                return;

            for (int i = 0; i < colCount; i++)
            {
                var group = ValidatorGroups[i];
                if (group == null || group.Length == 0)
                    continue;

                foreach (var validator in group)
                {
                    if (validator == null)
                        continue;

                    row[i] = validator.Validate(row[i], Strategies[i], BuilderGroups[i], row);
                }
            }
        }
    }
}
